package com.hfi.tx;

import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.interceptor.TransactionInterceptor;

import java.util.Properties;

/**
 * @author ChangLiang
 * @date 2019/6/3
 */
@Configuration
public class AspectjTransactionConfig {

    public static final String transactionExecution = "execution(* com.hfi.service..*.*(..))";

    @Autowired
    private PlatformTransactionManager transactionManager;

    /**
     * 定义增强类
     * @return
     */
//    @Bean
    public DefaultPointcutAdvisor defaultPointcutAdvisor() {
        // 指定不同的方法用不同的策略 查询基本上不需要事务支持
        Properties attributes = new Properties();
//        attributes.setProperty("get*", "PROPAGATION_REQUIRED,-Exception");
        attributes.setProperty("add*", "PROPAGATION_REQUIRED,-Exception");
        attributes.setProperty("save*", "PROPAGATION_REQUIRED,-Exception");
        attributes.setProperty("update*", "PROPAGATION_REQUIRED,-Exception");
//        attributes.setProperty("select*", "PROPAGATION_REQUIRED,-Exception");

        // 创建interceptor 其实就相当于Aspect 切面 定义在什么时间执行什么功能
        TransactionInterceptor interceptor = new TransactionInterceptor(transactionManager, attributes);

        // 定义切点：指定一般要拦截哪些类 定义在哪里执行
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression(transactionExecution);

        // 配置增强类advisor
        DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor();
        advisor.setPointcut(pointcut);
        advisor.setAdvice(interceptor);
        return advisor;
    }
}
